package hu.debrecen.adastra.card.service.domain;

import hu.debrecen.adastra.card.repository.domain.Account;

import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.google.common.collect.Iterables;

public class Round {

	private final Map<Card, Account> cards = new LinkedHashMap<Card, Account>();

	private Account winner;

	private final List<Account> callOrder;

	private int index = 0;

	public Round(final List<Account> callOrder) {
		this.callOrder = callOrder;
	}

	public void nextPlayer() {
		this.index = this.computeNextIndex(this.index);
	}

	public Account getNextPlayer() {
		return this.callOrder.get(this.computeNextIndex(this.index));
	}

	public Account getActualPlayer() {
		return this.callOrder.get(this.index);
	}

	public boolean isFirstCard() {
		return this.cards.size() == 1;
	}

	public Card getFirstCard() {
		return Iterables.getFirst(this.cards.keySet(), null);
	}

	public List<Card> getCards() {
		return new LinkedList<Card>(this.cards.keySet());
	}

	public Account getWinner() {
		return this.winner;
	}

	public void setWinner(final Account winner) {
		this.winner = winner;
	}

	public void putOnTable(final Account account, final Card card) {
		this.cards.put(card, account);
	}

	public Account getNextPlayer(final Account player) {
		int playerIndex = this.callOrder.indexOf(player);
		return this.callOrder.get(this.computeNextIndex(playerIndex));
	}

	private int computeNextIndex(final int index) {
		return (index + 1) % this.callOrder.size();
	}

}